package com.jxb.demo.controller;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPObject;
import com.jxb.demo.es.entity.OrderEntity;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.common.unit.Fuzziness;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.sort.SortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.completion.CompletionSuggestionBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.document.Document;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.UpdateQuery;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/search")
public class SearchController {

    private static Logger logger = LoggerFactory.getLogger(SearchController.class);

    @Resource
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    @PostMapping("/searchEs")
    public Object searchEs(@RequestBody OrderEntity param){
        logger.info("#####DemoController.searchEs####====>START");
        Object result = "Success";
        //搜索
        //1 创建QueryBuilder对象，使用QueryBuilders[不同类型搜索]
        //2 创建searchQuery【使用NativeSearchQuery】
        //字符串范围查询--需要keyword类型[字符串排序及范围搜索，使用keyword]
        //RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("orderDate.keyword").gt(param.getOrderDate());
        //RangeQueryBuilder rq2 = QueryBuilders.rangeQuery("orderPrice").from(1,false).to(10,false);
        //精确查询
        TermQueryBuilder tq = QueryBuilders.termQuery("orderId.keyword","ws-199230");
        //全文检索
        QueryBuilder mq = QueryBuilders.matchQuery("remark","二月").operator(Operator.AND).minimumShouldMatch("75%");
        //单字符串多字段查询
        QueryBuilder mmq = QueryBuilders.multiMatchQuery("离离原上草","orderAddr","remark");
        //短语查询
        MatchPhraseQueryBuilder mpq = QueryBuilders.matchPhraseQuery("remark","大唐");
        //前缀查询
        QueryBuilder pq = QueryBuilders.prefixQuery("orderId.keyword","ws-");
        //模糊搜索【相似度查询】
        QueryBuilders.fuzzyQuery("remark","月").transpositions(true);
        //通配符查询
        QueryBuilder wq = QueryBuilders.wildcardQuery("orderId","ws*");
        QueryBuilder wq2 = QueryBuilders.wildcardQuery("orderAddr.keyword","*开发区");
        //布尔查询
        QueryBuilder bq = QueryBuilders.boolQuery().must(wq).must(wq2);
        //模糊查询
        String []  text = {"离离原上草"};
        QueryBuilder mtq =  QueryBuilders.moreLikeThisQuery(text);
        QueryBuilders.moreLikeThisQuery(new String[]{"东营"});


        QueryBuilders.matchQuery("orderId","abc");
        SortBuilder sortBuilder = SortBuilders.fieldSort("orderDate.keyword").order(SortOrder.ASC);
        SortBuilder sortBuilder1 = SortBuilders.fieldSort("orderId.keyword").order(SortOrder.ASC);
        //PageRequest pageRequest = PageRequest.of(1,10);
        NativeSearchQuery searchQuery = new NativeSearchQueryBuilder()
                .withQuery(bq)
                .withSort(sortBuilder)
                .withSort(sortBuilder1)
                //.withPageable(pageRequest)
                .build();

        SearchHits<OrderEntity> searchHits = elasticsearchRestTemplate.search(searchQuery,OrderEntity.class);
        //分页
//        Map<String,Object> params = new HashMap<>();
//        params.put("orderAddr","青岛市胶州波尔多小镇");
//        //修改文档，将对象 转换成 map
//        //批量修改
//        Document document = Document.from(params);
////        document.setId("1");
//        UpdateQuery updateQuery = UpdateQuery.builder("1").withDocument(document).withDocAsUpsert(true).withTimeout(TimeValue.timeValueSeconds(1).toString()).build();
//        IndexCoordinates indexCoordinates = IndexCoordinates.of("order");
//        elasticsearchRestTemplate.update(updateQuery,indexCoordinates);


        List<SearchHit<OrderEntity>> hitList =  searchHits.getSearchHits();
        for(SearchHit<OrderEntity> hit:hitList){

            System.out.println("content:"+JSONObject.toJSONString(hit.getContent()));
        }

        logger.info("#####DemoController.searchEs####====>END");
        return result;
    }

    /**
     * @desc 删除索引
     * @param index
     * @return
     */
    @PostMapping("/delIndex")
    public Object delIndex(@RequestParam String index){
        Object result = null;
        IndexCoordinates indexCoordinates = IndexCoordinates.of(index);
        result  = elasticsearchRestTemplate.indexOps(indexCoordinates).delete();
        logger.info("#####删除索引：{}####",index);
        return result;
    }


}
